我们先来看看 vue 是怎么使用的?
- import Vue from 'vue'
- const App = new Vue({
- el: '#app',
- template: '<h1>{{msg}}</h1>',
- data: {
- msg: 'this is h1'
- }
- })
我们可以看到, 我们是通过 new 一个 Vue 对象, 并给对象传值的方式来使用的. App 则是 Vue 对象的一个实例, 既然是对象, 那肯定有属性和方法.
我们先来说说 Vue 中有哪些属性
- console.log('data', App.msg) // this is h1
- console.log('$data', App.$data) // {
- msg: 'this is h1'
- }
- console.log('$props', App.$props) // undefined
- console.log('$el', App.$el) // <h1>this is h1</h1>
- console.log('$options', App.$options) //
- console.log('$root', App.$root) //
- console.log('$children', App.$children) // []
- console.log('$slots', App.$slots) // {
- }
- console.log('$scopedSlots', App.$scopedSlots) // {
- }
- console.log('$refs', App.$refs.h1) //<h1>this is update h1 again</h1>
props 是子组件用来接收父组件传值的一个属性, 这里我们并没有子组件, 所以没有 props.
children 也是查看子组件的, 这里也没有.
slots(插槽的概念) 后面会单独将, 还是挺重要的.
当然想看的话也是可以的. 我们把配置修改一下, 引入一个子组件., 然后在子组件中接收一下 props
- const App = new Vue({
- el: '#app',
- components: {App},
- template: '<div><h1>{{msg}}</h1><App :test="msg"/></div>',
- data: {
- msg: 'this is h1'
- }
- })
children 数组就有值了.
然后我们可以用 App.prop 查看子组件的 props 的值
我们再来看看 Vue 实例有哪些方法?
1.App.
watch() 需要自己手动销毁, 而组件里面的 watch 是会自动销毁的.
销毁方式也很简单, 调用一下返回的函数即可.
- let unWatch = App.$watch() // 作用跟 watch 的效果是一样的, watch 中会自动销毁
- unWatch() // 销毁
举个例子:
- setInterval(()=> {
- App.msg += '1'
- },1000)
- let unWatch = App.$watch('msg', (n,o)=> {
- console.log(n,o)
- })
加上销毁, 输出结果就变成了 2 条记录.
- setTimeout(()=> {
- unWatch() // 销毁
- },2000)
2.App.$on() 监听事件, App.emit() 触发事件, 但是他们必须对同一个 vue 对象起作用, 而且不会冒泡.
- // 必须同一个对象
- App.$on('test', (m,n)=> {
- console.log('this is test', m , n)
- }) // 触发事件
- App.$emit('test', 1 ,2) //
结果: this is test 1 2
子组件向父组件传递方法其实就是这种用法.
3.App.
forceUpdate() 强制重新渲染页面, 比如修改对象里面的某些值的时候, 这时候试图可能不会同步更新, 就可以用 App.$forceUpdate() 强制渲染一下 (一般不用)
一般修改值需要重新渲染的时候, 我们都会通过 App.$set 来进行.
5.App.$nextTick() 当 dom 元素发生改变的时候会调用这个函数, 这个函数还是非常好用的, 比如动态的微调一些样式.
来源: http://www.jianshu.com/p/e8808df4cfe1