×

vue组件应用:以插件的形式使用组件

作者:andy0012021.09.24来源:Web前端之家浏览:4299评论:0
关键词:vuejs

学下vue组件应用:以插件的形式使用组件。有时候在开发过程中,由于项目需求,部分相同的代码我们会封装成组件,在需要使用的地方导入,并以标签的形式书写在中。

以插件的形式使用组件:

// 将要显示的组件导入
import mymodel from '../components/mymodel.vue'
export default {
  install: function (Vue) {
    // 1.0 根据 mymodel 组件对象得到它的构造函数
    const Mymodel = Vue.extend(mymodel)
    // 给所有的 vue 实例添加一个方法 $model
    Vue.prototype.$model = function () {
      // 为了显示一个组件: mymodel
      // 2.0 创建一个组件对象
      const obj = new Mymodel()
      // 3.0 将组件显示出来
      obj.show = true
      // 4.0 得到组件对象的 html 结构
      const html = obj.$mount().$el
      // 5.0 将 html 结构渲染到页面上
      document.body.append(html)
    }
  }
}

应用起来:

<template>
  <div>
    <h3>以普通组件的方法来调用</h3>
    <button @click="fn1">show Model</button>
    <!-- <mymodel :value="show" @input="val => (show = val)"></mymodel> -->
    <mymodel v-model="show"></mymodel>
    <!-- sync:向组件内传入了参数: xxx 从组件中接收了事件:update:xxx 事件会自动修改 xxx -->
    <!-- v-model:向组件内传入了参数: value 从组件中接收了事件:input 事件会自动修改 value -->
    <h3>以 js 方式来调用</h3>
    <button @click="fn2">show Model</button>
  </div>
</template>
<script>
import mymodel from '../../components/mymodel.vue'
export default {
  data () {
    return {
      show: false
    }
  },
  methods: {
    fn1 () {
      this.show = true
    },
    fn2 () {
      // 通过 js 的方法直接将组件显示出来
      this.$model()
    }
  },
  components: {
    mymodel: mymodel
  }
}
</script>
 
<style></style>

试试吧!!!

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vuejs20210924a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: