为实例property设置作用域

本文探讨了在Vue应用中如何确保全局属性如`$appName`和`$test`在所有实例中可用,以及如何避免与组件内数据冲突。通过在原型上添加属性,可以在Vue实例生命周期的各个阶段访问这些属性。当在`beforeCreate`钩子中引用未在当前实例定义的属性时,将从原型链中查找。如果在同一作用域内存在同名数据属性,后者会覆盖前者。因此,使用`$`前缀作为约定,以区分实例级属性和局部数据,防止命名冲突。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:希望数据在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值