FE_Vue框架的重要属性讲解【ref props mixin】

1 ref属性

对于传统的HTML而言,id 和 ref确实没有什么差别,但是对于组件来说就不一样了。给组件加id,打印出获取的结果为组件所对应的完整DOM结构。给组件加ref,打印出获取的结果就是VueComponent实例。

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:应用在html标签上获取的是真实DOM元素
<h1 v-text="msg" ref="title"></h1>
this.$refs.title
<template>
  <div>
    <h1 id="title" v-text="msg" ref="title"></h1>
    <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
  </div>
</template>
<script>
export default {
  methods: {
    showDOM() {
      console.log(document.getElementById('title')) // sout : <h1 id="title">Hello zhaoshuai-lc</h1>
      console.log(this.$refs.title) // sout : <h1 id="title">Hello zhaoshuai-lc</h1>
    }
  }
}
</script>
  1. 使用方式:应用在组件标签上是组件实例对象(vc)
<template>
  <div>
    <HelloWorld ref="hello"/>
    <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  methods: {
    showDOM() {
      console.log(this.$refs.hello)
    }
  }
}
</script>

在这里插入图片描述

2 props属性

2.1 父组件给子组件传值

在这里插入图片描述

学生名字:zhaoshuai-lc
学生性别:male
学生年龄:26

2.2 但是这里会出现一个问题:假设我们给父组件传过来的值{{ age + 1 }}

在这里插入图片描述
这里是父组件传值 :这里导致的问题

<template>
  <div>
    <HelloWorld ref="hello" z_name="zhaoshuai-lc" z_gender="male" z_age="26"/>
  </div>
</template>

解决方案:加一个冒号

:z_age="" 
"作为表达式"
<HelloWorld ref="hello" z_name="zhaoshuai-lc" z_gender="male" :z_age="26"/>

2.3 万一父组件传值没有注意呢?我们应该子组件也加一个限制,对子组件props 的格式做调整:

  props: {
    z_name: String,
    z_gender: String,
    z_age: Number
  },

还可以更加精确:

  props: {
    z_name: {
      type: String,
      required: true
    },
    z_gender: {
      type: String,
      required: true,
      default: 'male'
    },
    z_age: {
      type: Number,
      required: true,
      default: 100
    },
  },

2.4 props是只读的,值是不能修改的

props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
在这里插入图片描述

3 mixin属性

不同组件之间的代码重复问题 - mixin可以把多个组件共用的配置提取成一个混入对象

在这里插入图片描述
在这里插入图片描述
在混合中写周期函数,即复用配置的做法:原则:

  1. 对于data的而言,自己有则用自己的,若没有的话就用混合中的
  2. 但是对于生命周期函数,不以任何为主,周期函数都要【混合在前,自己在后】

在这里插入图片描述

import Vue from 'vue'
import App from './App.vue'
import {mixin, data} from './mixin'
Vue.config.productionTip = false
Vue.mixin(mixin)
Vue.mixin(data)
new Vue({
    render: h => h(App),
}).$mount('#app')

4 plugins 属性

功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。

在这里插入图片描述

我们可以发现install的第一个参数为vue实例对象:

@@@install,  ƒ Vue(options) {
  if ( true && !(this instanceof Vue)) {
    warn('Vue is a constructor and should be called with the `new` keyword');
  }
  this._init(options);
}

利用这一点,我们可以做很多事情:
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>