vue构建单页面应用实战

2020-06-16 05:54:27易采站长站整理

attached:function(){
console.log("attached..");
},

//在 vm.$el 从 DOM 中删除时调用。必须是由指令或实例方法删除,直接操作 vm.$el 不会 触发这个钩子。
detached:function(){
console.log("detached..");
},

//在开始销毁实例时调用。此时实例仍然有功能。
beforeDestroy:function(){
console.log("beforeDestroy..");
},

//在实例被销毁之后调用。此时所有的绑定和实例的指令已经解绑,所有的子实例也已经被销毁。如果有离开过渡,destroyed 钩子在过渡完成之后调用。
destroyed:function(){
console.log("destroyed..");
}

};

在浏览器里执行了看看:

首次进入 List 页面的执行顺序如下:

 

此时点一下浏览器的后退,List Component 会被销毁,执行顺序如下:

 

这是官方的生命周期的图:

 

10. 父组件与子组件

在很多情况下,组件是有父子关系的,比如 list 列表组件有个子组件 item

components/item.js


module.exports = {
template: require('../templates/item.html'),

props:["id","name"],

ready: function () {

}
};

templates/item.html


<p>我是subitem: ${id} - ${name}</p>

修改 list 组件,添加 item 的引用

components/list.js


//引用item组件
import item from "./item";

module.exports = {
template: require('../templates/list.html'),

data:function(){
return {items:[{"id":1,"name":"hello11"},{"id":2,"name":"hello22"}]};
},

//定义item组件为子组件
components:{
"item":item
},

ready: function () {
}

};

templates/list.html


<h1>List</h1>
<hr/>
<p>Hello List Page!</p>
<ul>
<li v-for="(index,item) in items">
<!--使用item子组件,同时把id,name使用props传值给item子组件-->
<item v-bind:id="item.id" v-bind:name="item.name"></item>
</li>
</ul>

浏览器里试试看:

 

子组件成功被调用了