【Vue】全局API之Vue.extend讲解用法

Vue.extend( options )

该方法通俗点讲就是可以将你的vue模板代码单独使用,vue扩展性的一个体现,因为一般你的项目中只有一个 new Vue(),比如这时候让你用vue模板技术实现一个全局消息提示函数 hint(),怎么做?先看一个简单demo

// Vue.extend 简单入门示例
const Com = Vue.extend({
  template: `<h1 @click="handleClick">{{msg}}</h1>`,
  data() {
    return {
      msg: 'Hello Vue.extend'
    }
  },
  methods: {
    handleClick() {
      this.msg = this.msg.split('').reverse().join('')
    }
  }
})
document.body.appendChild(new Com().$mount().$el)
Vue.extend()参数跟创建组件一个,是一个配置对象,会返回一个vue组件构造器,我们可以实例它获取到它的组件实例对象,从而调用$mount()方法获取它有挂载点的vm实例,
在调用 $el()方法获取道dom对象,然后添加道body,结果如下:


简单案例实现 hint 提示函数
function hint({ title = '', content = '' }) {
  const Hint = Vue.extend({
    template: `<div v-if="isHide"><h3>{{title}}</h3>{{content}}</div>`,
    data() {
      return {
        title: title,
        content: content,
        isHide: true
      }
    },
    mounted() {
      setTimeout(() => (this.isHide = false), 1000)
    }
  })
  const h = new Hint()
  document.body.appendChild(h.$mount().$el)
}

hint({
  title: 'Notice',
  content: 'Hello Hint!'
})

显示提示然后 2秒后消失

原文地址:https://www.cnblogs.com/bc8web/p/5767548.html