Vue 综合-基础加强

128 阅读1分钟

如果需要在 new Vue({template: <div>测试</div>}).$mount('#app') 中使用并显示 template 需要按照这样配置一下。

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

const app = new Vue({
  // router,
  // store,
  // render: h => h(App)
  template: '<div>{{text}}</div>',
  data:{
    text: 0
  },
  // render (h) { // 这种写法就跟上面的 template 写法的效果一样,也是上面 render 的写法。
  //   return h('div', {}, this.text)
  // }
  // watch: { // 这样写则不需要手动释放
  //   text (newText, oldText) {
  //     console.log(`${newText} : ${oldText}`)
  //   }
  // }
})


// 挂载到app节点
app.$mount('#app')


// 定时修改数据使页面发生变化
setInterval(() => {
  app.text += 1
}, 1000);


// 手动编写 render 方法,但是它只能在页面发生变化重新渲染的时候生效
app.$options.render = (h) => {
  return h('div', {}, 'asd')
}


// 所有地方拿到的 $root 都是同一个值
console.log(app.$root === app); // true 


// watch 监听方法,如果在外部这样写,是需要自己手动释放的,默认会返回 unWatch 释放方法。
const unWatch = app.$watch('text', (newText, oldText) => {
  console.log(`${newText} : ${oldText}`)
})
// 手动释放
setTimeout(() => {
  unWatch()
}, 2000);


// on 监听 test 事件
app.$on('test', (a, b) => {
  console.log(`on test emit ${a} ${b}`)
})
// once 监听 test 事件, 它只会监听一次
app.$once('test', (a, b) => {
  console.log(`once test emit ${a} ${b}`)
})
// 调用
setInterval(() => {
  app.$emit('test', 1, 2)
}, 1000);


// 强制重新渲染
// 如果添加修改一个没有在 $data 里面初始的属性字段,并且使用到,那么就需要用到强制更新
// 因为没有初始化的字段你无论怎么变更都不会触发更新机制,所以只能手动强制更新
app.$forceUpdate()
// 但是可以使用 $set 进行赋值更新
app.$set(object, key, value) // 例如: app.$set(app.obj, 'temp', 1)
// 删除属性也是一样的需要用到 $delete 才可以彻底删除,要不然会内存溢出
app.$delete(object, key) // 例如: app.$delete(app.obj, 'temp')


// Dom 节点下次更新的时候调用
app.$nextTick(callback)