先上图:
示例代码:
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Title
- </title>
- </head>
- <body>
- <script type="text/javascript" src="vue.js">
- </script>
- <div id="app">
- </div>
- <script type="text/javascript">
- var mytest = {
- template: ` < div > 测试 {
- {
- msg
- }
- } < br > <button@click = "msg+='1'" > 点一下数据会更新 < /button>
- </div > `,
- data() {
- return {
- msg: '嗯呢'
- }
- },
- // 组件创建前
- beforeCreate() {
- console.log('组件创建前') console.log(this.msg)
- },
- // 组件创建后
- created() {
- console.log('组件创建后') console.log(this.msg)
- },
- // Dom 挂载前
- beforeMount() {
- console.log('Dom 挂载前') console.log(document.body.innerText)
- },
- // Dom 挂载后
- mounted() {
- console.log('Dom 挂载后') console.log(document.body.innerText)
- },
- // 数据变更前
- beforeUpdate() {
- console.log('数据更新前') console.log(document.body.innerText)
- },
- // 数据变更后
- updated() {
- console.log('数据更新后') console.log(document.body.innerText)
- },
- // 组件销毁前
- beforeDestroy() {
- console.log('组件销毁前')
- },
- // 组件销毁后
- destroyed() {
- console.log('组件销毁后')
- },
- // 组件激活
- activated() {
- console.log('组件激活')
- },
- // 组件停用
- deactivated() {
- console.log('组件停用')
- }
- }
- new vue({
- el: '#app',
- template: ` < div > <keep - alive > <mytest v -
- if = "mytestShow" > </mytest></keep - alive > <button@click = "clickDestroy" > 组件销毁 < /button>
- </div > `,
- components: {
- mytest
- },
- data() {
- return {
- mytestShow: true
- }
- },
- methods: {
- clickDestroy() {
- this.mytestShow = !this.mytestShow
- }
- }
- })
- </script>
- </body>
- </HTML>
在需要频繁的创建和销毁组件, 如果用的是 v-if, 可以使用 activated()deactivated() 对组件进行激活和停用, 前提是被操作组件要用 < keep alive></keep alive > 包裹
例:<keep-alive><mytest v-if="mytestShow"></mytest></keep-alive>
来源: http://www.bubuko.com/infodetail-3075186.html