×

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

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

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

以插件的形式使用组件:

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

应用起来:

  1. <template>
  2.   <div>
  3.     <h3>以普通组件的方法来调用</h3>
  4.     <button @click="fn1">show Model</button>
  5.     <!-- <mymodel :value="show" @input="val => (show = val)"></mymodel> -->
  6.     <mymodel v-model="show"></mymodel>
  7.     <!-- sync:向组件内传入了参数: xxx 从组件中接收了事件:update:xxx 事件会自动修改 xxx -->
  8.     <!-- v-model:向组件内传入了参数: value 从组件中接收了事件:input 事件会自动修改 value -->
  9.     <h3>以 js 方式来调用</h3>
  10.     <button @click="fn2">show Model</button>
  11.   </div>
  12. </template>
  13. <script>
  14. import mymodel from '../../components/mymodel.vue'
  15. export default {
  16.   data () {
  17.     return {
  18.       show: false
  19.     }
  20.   },
  21.   methods: {
  22.     fn1 () {
  23.       this.show = true
  24.     },
  25.     fn2 () {
  26.       // 通过 js 的方法直接将组件显示出来
  27.       this.$model()
  28.     }
  29.   },
  30.   components: {
  31.     mymodel: mymodel
  32.   }
  33. }
  34. </script>
  35.  
  36. <style></style>

试试吧!!!

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

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

发表评论: