并不是对官方文档的再汇总,只是在读教程的时候,记一下之前忽略掉的官方内容
computed计算属性的setter函数
// ...computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}}// ..
用 key 管理可复用的元素
//Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。
<template v-if="loginType === 'username'">
<label>Username</label>
<input placeholder="Enter your username">
</template>
<template v-else>
<label>Email</label>
<input placeholder="Enter your email address">
</template>
那么在上面的代码中切换 loginType 将不会清除用户已经输入的内容。
因为两个模板使用了相同的元素,<input> 不会被替换掉——仅仅是替换了它的 placeholder
所以 Vue 为你提供了一种方式来表达“这两个元素是完全独立的,不要复用它们”。
只需添加一个具有唯一值的 key attribute 即可:
<template v-if="loginType === 'username'">
<label>Username</label>
<input placeholder="Enter your username" key="username-input">
</template><template v-else>
<label>Email</label>
<input placeholder="Enter your email address" key="email-input">
</template>
注意,<label> 元素仍然会被高效地复用,因为它们没有添加 key attribute。
重新绑定v-model默认语法糖
v-model的默认语法糖是
:value="inputText"
@input="inputText=$event"
但是有时封装组件的时候,用到的并不是input与value。如何用v-model的语法糖语法,封装自己组件适用的prop和事件,可以在子组件上使用model属性修改默认。
比如checkbox,radio,选择属性由checked控制,value用于提交表单。选择属性改变触发的是change事件。这个时候默认的value与input事件都不再符合场景。
在子组件中 使用model属性可以修改父组件的v-model默认绑定的value值与input事件
Child:
export default:{
model:{
prop:'inp',
event:"change"
}
}
此时Father中的v-model
相当于
注意 记得在props中定义inp的值,需要修改inp绑定的值,this.$emit('change',modifyValue)
或者官网上的例子:
Vue.component('base-checkbox', { model: { prop: 'checked', event: 'change' }, props: { checked: Boolean }, template: ` <input type="checkbox" v-bind:checked="checked" v-on:change="$emit('change', $event.target.checked)" > `})
<base-checkbox v-model="lovingVue"></base-checkbox>
关于listeners
作用:attrs用来传递prop listener用于传递事件
数据流向:从上向下流
举例:
$attrs:收集父组件中未被prop识别的attribute绑定(class和style除外)
//爷组件:
<GrandFather>
//Father中不在props中接收这俩属性
<Father :age="age" :name="name"/>
</GrandFather>
//父组件:
<Father
//当Father组件中的props中并没有接收age、name时,可以GrandSon组件使用$attrs获取
<GrandSon :name="$attrs.name" :age="$attrs.age"/>
//或者直接全部接收
<GrandSon v-bind="$attrs"/>
//注意:GrandSon组件如果用v-bind="$attrs"这种方式的话,//需要在GrandSon组件中添加inheritAttrs:false(避免父作用域不被认作props的属性绑定在子组件的根元素上)</Father>
$listeners
$listeners包含了父组件中的事件监听器(v-on / @),可以用v-on做更深层次的传递
使用方法与listeners,或者可以用v-on全部监听
<GrandFather >
<Father @customClick="clickFun"/>
</GrandFather>
Father:
<template>
//<div @click="$emit('customClick')"> </div>
//或者
<div @click="$listeners.customClick"></div>
//对于想把事件传给孙子组件时
<GrandSon v-on="$listeners"/>
</template>
GrandSon:
<template>
<div @click="$listeners.customClick"></div>
</template>