大前端程序员

vue用法指南02(Vue实例)

2019-03-01  本文已影响66人  Mr绍君

我们先来看看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.children[0].prop查看子组件的props的值

我们再来看看Vue实例有哪些方法?

1.app.watch() 这个方法的作用跟直接在组件里面的watch是一样的,但是还是会有差别,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.once监听事件,但是只能触发一次 4.app.forceUpdate()强制重新渲染页面,比如修改对象里面的某些值的时候,这时候试图可能不会同步更新,就可以用app.$forceUpdate()强制渲染一下(一般不用)

一般修改值需要重新渲染的时候,我们都会通过app.$set来进行。

5.app.$nextTick()当dom元素发生改变的时候会调用这个函数,这个函数还是非常好用的,比如动态的微调一些样式。

上一篇 下一篇

猜你喜欢

热点阅读