目的:希望数据在Vue的所有实例中都可以使用。
Vue.prototype.$appName = 'My App'
$appName在Vue实例创建之前就可以使用。
main.js
import Vue from 'vue'
import App from './App'
Vue.prototype.$test = 'test'
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
App.vue
<script>
export default {
beforeCreate: function() {
console.log(this.$test);
},
onLaunch: function() {
console.log("test onLaunch 01..............");
console.log(this.$test);
}
}
</script>
控制台打印结果:
test // from beforeCreate
test onLaunch 01.............. // from onLaunch
test // from onLaunch
$test 为何以$开头?
$是在VUE所有实例中都可用的property的一个简单约定。这样可以避免被定义的数据、方法、计算属性产生冲突。
复现冲突
main.js
import Vue from 'vue'
import App from './App'
Vue.prototype.test = 'test'
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
App.vue
<script>
export default {
data: {
test: 'this is a test'
},
beforeCreate: function() {
console.log(this.test);
},
onLaunch: function() {
console.log("test onLaunch 01..............");
console.log(this.test);
}
}
</script>
控制台打印结果:
test // from beforeCreate (main.js)
test onLaunch 01.............. // from onLaunch (App.vue)
this is a test // from onLaunch (App.vue)
App.vue 与 main.js同时包含变量test,加载App.vue时,App.vue中的test值会覆盖main.js中的test值。
$为实例property设置作用域来避免冲突发生。
复现问题:undefined
main.js
import Vue from 'vue'
import App from './App'
Vue.prototype.$test = 'test'
App.mpType = 'app'
const app = new Vue({
store,
...App
})
app.$mount()
App.vue
<script>
export default {
data: {
test: 'this is a test'
},
beforeCreate: function() {
console.log(this.test);
},
onLaunch: function() {
console.log("test onLaunch 01..............");
console.log(this.test);
}
}
</script>
控制台打印结果:
undefined // from beforeCreate (main.js does has $test rather than test)
test onLaunch 01.............. // from onLaunch (App.vue)
this is a test // from onLaunch (App.vue)
beforeCreate 是创建App.vue之前加载来自main.js中的变量值,如果main.js不存在该变量,则返回undefined。
参考:https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html
本文探讨了在Vue应用中如何确保全局属性如`$appName`和`$test`在所有实例中可用,以及如何避免与组件内数据冲突。通过在原型上添加属性,可以在Vue实例生命周期的各个阶段访问这些属性。当在`beforeCreate`钩子中引用未在当前实例定义的属性时,将从原型链中查找。如果在同一作用域内存在同名数据属性,后者会覆盖前者。因此,使用`$`前缀作为约定,以区分实例级属性和局部数据,防止命名冲突。
1530

被折叠的 条评论
为什么被折叠?



