Set the scope for the instance property

Purpose: Hope that the data can be used in all instances of Vue.

Vue.prototype.$appName = 'My App'

$appNameIt can be used before the Vue instance is created.

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()

View app

<script>
	export default {
		beforeCreate: function() {
			console.log(this.$test);
		},
		onLaunch: function() {
			console.log("test onLaunch 01..............");
			console.log(this.$test);	
		}
	}
</script>

The console prints the result:

test // from beforeCreate
test onLaunch 01.............. // from onLaunch
test // from onLaunch

Why does $test start with $?

$ Is a simple convention for properties available in all instances of VUE. In this way, conflicts between defined data, methods, and calculated attributes can be avoided.

Recurring conflict

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()

View app

<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>

The console prints the result:

test // from beforeCreate (main.js)
test onLaunch 01.............. // from onLaunch (App.vue)
this is a test // from onLaunch (App.vue)

Both App.vue and main.js contain the variable test. When App.vue is loaded, the test value in App.vue will override the test value in main.js.

$ Set the scope for the instance property to avoid conflicts.

Recurring problem: 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()

View app

<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>

The console prints the result:

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 is to load the variable value from main.js before creating App.vue. If the variable does not exist in main.js, it returns undefined.

Reference: https://cn.vuejs.org/v2/cookbook/adding-instance-properties.html

Guess you like

Origin blog.csdn.net/A_bad_horse/article/details/114011972