//
vue 源码 关于 props methods data computed watch 的执行顺序
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch);
}
}
可以看出 props->methods->data->computed->watch 执行顺序
*关于传值问题可以看另外一篇文章:*https://blog.csdn.net/zmx12100423/article/details/108127606
props
props可以是数组 || 对象,作用:用于接收来自父组件传递的数据。
props 可以配置类型检测、自定义验证和设置默认值。
实例
export default {
name:"Child",
//props: ['title', 'likes', 'isPublished', 'commentIds', 'author'],
props:{
// 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
title:{
type:Array, // 类型检测 //[String, Number],多个类型检测
default:()=>{ // 对象或数组默认值必须从一个工厂函数获取
return new Array() //默认是一个数组
}
},
likes:{
type:Object,
default:()=>{
return new Object()
}
},
// 必填的字符串
isPublished: {
type: String,
required: true // 必须
},
},
data() {}
}
methods
methods的类型是:{ [ key : string ] : Function } ,
methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例。
export default {
data(){
return {
},
mounted() {
this.list(); //挂载实例方法 实例的方法可以挂载到created mounted 里 函数//只执行一次 自定义方法根据需要挂载到methods中
},
methods:{
list(){
console.log("测试")// “测试”
}
}
}
}
data
data的类型:Object || Function 组件的定义只接受 function
实例
//组件中的data
export default {
data(){
return {
name:"小明"
}
}
}
data:Vue实例的数据对象。Vue将会递归将data的property转换为getter.setter,从而让data的property能够影响数据的变化。对象必须是纯粹的对象 (含有零个或多个的 key/value 对).
computed
计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。计算属性的结果会被缓存,除非依赖的响应式 property 变化才会重新计算。注意,如果某个依赖 (比如非响应式 property) 在该实例范畴之外,则计算属性是不会被更新的。
watch
类型:{ [key: string]: string | Function | Object | Array }
一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个 property。
实例
var vm = new Vue({
data: {
a: 1,
b: 2,
c: 3,
d: 4,
e: {
f: {
g: 5
}
}
},
watch: {
a: function (newVal, oldVal) {
console.log(newVal, oldVal)
},
// 方法名
b: 'someMethod',
// 该回调会在任何被侦听的对象的 property 改变时被调用,不论其被嵌套多深
c: {
handler: function (newVal, oldVal) { /* ... */ },
deep: true //深度监听 数组或对象内部发生改变也可以监听到
},
// 该回调将会在侦听开始之后被立即调用
d: {
handler: 'someMethod',
immediate: true
},
// 你可以传入回调数组,它们会被逐一调用
e: [
'handle1',
function handle2 (newVal, oldVal) { /* ... */ },
{
handler: function handle3 (newVal, oldVal) { { /* ... */ },
}
]
}
})
随笔写一下感受吧