vue2 - 生命周期钩子,ref属性,mixins属性 局部使用与全局使用

1.生命周期钩子

 

 

<script>
  new Vue({
    beforeCreate() {
      console.log('beforeCreate')
    },
    created() {
      console.log('created')
    },
    beforeMount() {
      console.log('beforeMount')
    },
    mounted() {
      console.log('mounted 常用')
    },
    beforeUpdate() {
      console.log('beforeUpdate')
    },
    updated() {
      console.log('updated')
    },
    beforeDestroy() {
      console.log('beforeDestroy')
    },
    destroyed() {
      console.log('destroyed 常用')
    },
  })
</script>

 

2.ref属性

替代DOM原生操作中的id获取元素,ref还可以获取组件(VueComponent )

<div id="app">
    <p ref="say">hello,world</p>
  </div>

<script>
  const vue=new Vue({
    el: '#app',
    methods: {
      getElement(){
        //获取ref为say的element
        console.log(this.$refs.say)
      }
    }
  })
</script>

 

3.mixins属性

mixin混合就是把一些公共的属性与方法抽取出来,要使用时即可方便使用

1.定义公共的属性与方法 - mixin.js

export const mixinFn={
 //公共的方法
  methods: {
    info(){
      //定义的公共的方法
      console.log("我是mixin中的共享方法")
    }
  },
  //生命周期
  mounted() {
    //生命周期方法
  },
  beforeDestroy() {
    //生命周期方法
  }
}

export const mixinData={
  data(){
    return {
      //公共的属性
      name: 'levi',
      age: 18
    }
  }
}

2.导入mixin.js并且mixins属性使用公共的方法与属性 局部使用

<script>
  import {mixinFn,mixinData} from "./mixin";

  export default {
    data(){
      return{
        name: 'miakasa'
      }
    },
    //使用公共的属性与方法
    mixins: [mixinFn,mixinData]
  }
</script>

3.导入mixin.js并且.Vue.mixin属性使用公共的方法与属性 全局使用

所有的组件都有mixin里面的属性与方法,一般不建议使用

import Vue from 'vue'
import App from './App.vue'

//导入mixin
import {mixinFn,mixinData} from "./mixin";
//使用 所有的组件都有mixin里面的方法与属性
Vue.mixin(mixinFn)
Vue.mixin(mixinData)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

1.如果组件中的data中的属性或方法与mixin中的data中的属性或方法有冲突,优先使用当前组件中的属性或方法

2.如果生命周期方法有冲突时,组件与mixin中的方法都会执行,mixin中的方法先执行 组件中的方法后执行

posted on 2023-02-17 12:57  Mikasa-Ackerman  阅读(167)  评论(0编辑  收藏  举报

导航