vue添加實例屬性

你可能會在不少組件裏用到數據/實用工具,可是不想污染全局做用域。這種狀況下,你能夠經過在原型上定義它們使其在每一個 Vue 的實例中可用。vue

Vue.prototype.$appName = 'My App'

 

假如咱們全局定義一個實例屬性,這樣就能夠在全部vue實例中使用。webpack

例如:git

main.jsgithub

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

Vue.prototype.$appName = 'hello world' //全局定義一個實例屬性

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

HelloWorld.vue(這樣就能夠在各個vue實例中使用)web

<template>
  <div class="hello">
   	<button @click="handleClick">按鈕</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      appName: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
  		handleClick(){
  			let data = this.$appName;
  			console.log('kkkk',data); // hello world
  		}
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

注意:在這裏咱們能夠看到,在用原型去定義一個實例屬性的時候,咱們在屬性名的前方加了一個 '$',好比咱們剛纔定義的屬性名'appName'的前方就有一個'$',其實這麼作的目的就是:避免與在各個vue實例中已定義相同名稱的屬性發生衝突。app

假如咱們不加'$',會發生什麼狀況呢?工具

main.jsui

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

Vue.prototype.appName = 'hello world' //全局定義一個實例屬性

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

HelloWorld.vuethis

<template>
  <div class="hello">
   	<button @click="handleClick">按鈕</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      appName: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
  		handleClick(){
  			let data = this.appName;
  			console.log('kkkk',data); // Welcome to Your Vue.js App
  		}
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

從上面咱們能夠看出打印的結果是不同的,由於全局定義的屬性名與實例中定義的屬性名是相同的,因此你獲得的只是各個實例中的數據,而不是全局中想要獲得的數據,因此爲了區別開纔要加個‘$’,加什麼不重要,是隨意的,重要的是避免衝突。prototype

不是全局配置:

 HelloWorld.vue

<template>
  <div class="hello">
   	<button @click="handleClick">按鈕</button>
  </div>
</template>

<script>
import Vue from 'vue'
Vue.prototype.$exe = { //定義一個屬性
	num: '23'
}
export default {
  name: 'HelloWorld',
  data () {
    return {
      //appName:this.$exe.num 
    }
  },
  methods: {
  		handleClick(){
  			//let data = this.appName; //23
  			let data = this.$exe.num; //23
  			console.log('kkkk',data);
  		}
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
相關文章
相關標籤/搜索