先看一下VUE模版的最佳实践
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<p>{{msg}}</p>
</div>
<script>
var app = new Vue({
el: '#app',
data() {
return {
value: "1"
// ?????为什么必须函数 还要return回去 对象不行吗???????
};
},
methods: {
say: function () {
console.log('再给我两分钟!!');
}
},
beforeCreate: function () {
//new操作在这里面但是没有return
/*执行beforeCreate的时候,表示Vue刚刚出生,还没有任何内容data/methods都还没有初始化*/
console.log(this.msg);
// this.say();
// console.log(this.say());
},
created: function () {
/*在执行created的时候,表示Vue实例已经初始化好了部分内容,data/methods 想在Vue实例中最早访问到data/methods,只有在这个方法才能访问*/
console.log(this.msg);
this.say();
console.log(this.say);
},
beforeMount: function () {
/*执行beforeMount,表示已经根据数据编译好了模版,但是还没有渲染到页面上*/
console.log(document.querySelector('p').innerHTML);
},
mounted: function () {
/*执行mounted,表示已经根据数据编译好了模版,已经将模版有渲染到界面上,此时可以对界面进行其他操作了*/
console.log(document.querySelector('p').innerHTML);
},
beforeUpdate: function () {
/*主要是data中的数据发生了变化就会执行
执行beforeUpdate的时候,data的数据已经是最新的了,但是没有更新界面上的数据
*/
console.log(this.msg);// 打印不出来
console.log(document.querySelector("p").innerText);
console.log(document.querySelector("p").innerHTML);
},
updated: function () {
/*主要data中的数据发生了变化就会执行
执行updated的时候,data的数据已经是最新的了,界面上的数据也已经更新*/
console.log(this.msg);
console.log(document.querySelector("p").innerText);
console.log(document.querySelector("p").innerHTML);
},
destroyed: function () {
/*执行它的时候,表示Vue实例完全销毁,实例中的任何内容都不能被使用了*/
//使用场景 清空定时器和Ajax请求
}
})
</script>
</body>
</html>
2.其中Data返回的是一个对象,Vue为什么这样设计呢?
1-1:为了解释这个谜题 我们看下面这段代码
(1):第一种是 vue里面 尤雨溪设计的用法
function a() {
return {
name:'cluo',
age:18
}
}
let vuecomponent1 = a ()
let vuecomponent2 = a ()
let vuecomponent3 = a ()
vuecomponent1.name = '梅西'
console.log(vuecomponent1)
console.log(vuecomponent2)
console.log(vuecomponent3)
这里返回的是一个对象 每赋值一次,都会重新开辟一个内存空间,当更改其中一个中的值得时候,其他都不变,互不干扰。
这里的代码可以这样理解
(2):第二种是我们想试验的是否可行的用法
const obj = {
name:'cluo',
age:18
}
function a(){
return obj
}
let vuecomponent1 = a()
let vuecomponent2 = a()
let vuecomponent3 = a()
vuecomponent1.name ='梅西'
console.log(vuecomponent1)
console.log(vuecomponent2)
console.log(vuecomponent3)
这里的代码可以这样理解
这个就是引用的,obj只开辟了一个内存空间,每声明一个就是指针指向了那片内存空间。 当修改其中一个的时候,obj内存空间的值也对应修改 运行结果如下: