一.Vue实例
0.创建一个Vue实例
const app = new Vue({
// el: '#root',
template: '<div ref="div">{{text}} {{obj.a}}</div>',
})
app.$mount('#root') // 等同于el:"#root"
1.app.$mount
把dom节点挂载到body上,app.$mount('#root) 等同于再模板中写 el: '#root',
2.app.$data
获取在data中的数据,可以直接对数据操作
3.app.$props
父组件传入的数据, 组件相关的的属性
4.app.$el
获取挂载的节点dom
5.app.$options
我们创建的的options会和vue本身初始化的数据合并
app.$options.render方法
app.$options.render = (h) => { // render方法
return h('div', {}, 'new render function')
}
6.app.$root
整个Vue的实例,app.$root === app
7.app.$children
获取子组件
8.app.$slots
插槽,组件相关属性
9.app.$scopedSlots
作用域插槽 ,组件相关属性
10.app.$refs
如果在dom中获取当前dom节点,在组件上获取组件的实例,我们可直接调用组件的方法等。
11.app.$isServer
sr渲染会使用
二.Vue的api
1.app.$watch
2.app.$on
3.app.$emit
4.app.$forceUpdate() //强制组件刷新
5.app.$set 对象双向绑定
三.完整实例代码
// 01常见api
import Vue from 'vue'
const app = new Vue({
// el: '#root',
template: '<div ref="div">{{text}} {{obj.a}}</div>',
data: {
text: 0,
obj: {}
}
// watch: { // 自己会注销
// text (newText, oldText) {
// console.log(`${newText} : ${oldText}`)
// }
// }
})
app.$mount('#root') // 等同于el:"#root"
// let i = 0
setInterval(() => {
app.text += 1 // 能改变数据
// app.$data.text += 1 // 能改变数据
// app.$options.data.text += 1 //改变不了数据
// i++
// app.text += 1
// app.text += 1
// app.text += 1
// app.text += 1
// app.obj.a = i
// app.$set(app.obj, 'a', i)
// app.$forceUpdate()
// app.$data.text += 1
}, 1000)
console.log(app.$data) // 返回 自定义的数据
console.log(app.$props) // 父组件传入的数据, 组件相关的的属性
console.log(app.$el) // 挂载的节点
console.log(app.$options) //我们的options会和vue本身初始化的数据合并
// app.$options.render = (h) => { // render方法
// return h('div', {}, 'new render function')
// }
// console.log(app.$root === app) // vue的实例
// <com><div>123<div></com>
// console.log(app.$children) //<div>123<div>
// console.log(app.$slots) // 组件相关的属性
// console.log(app.$scopedSlots) // 组件相关的的属性
// console.log(app.$refs)
// console.log(app.$isServer) // ssr渲染会使用
/*
// const unWatch = app.$watch('text', (newText, oldText) => { // 自己调用的时候,需要注销,不然会导致内存溢出
// console.log(`${newText} : ${oldText}`)
// })
// setTimeout(() => {
// unWatch() // 注销
// }, 2000)
// app.$on('test', (a, b) => {
// console.log(`test emited ${a}`)
// })
// app.$emit('test', 1, 2)
app.$once('test', (a, b) => {
console.log(`test emited ${1} ${b}`)
})
setInterval(() => {
app.$emit('test', 1, 2)
}, 1000) */
// app.$forceUpdate() //强制组件刷新
// setInterval(() => {
// app.text += 1
// }, 100)
/*
vue实例:每个组件都是一个this === app
通过render编译template成HTML
*/