Vue.component

组件是可复用的 Vue 实例,且带有一个名字

因为组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。

// 定义一个名为 button-counter 的新组件
Vue.component('button-counter', {
   
  props: ['title'],
  data: function () {
   
    return {
   
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {
   { count }} {
   { title }}times.</button>'
})

注意当点击按钮时,每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。

一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝:

在input上使用 v-model

<input
  v-bind:value="searchText"
  v-on:input="searchText = $event.target.value"
>

在组件上使用 v-model

<custom-input
  v-bind:value="searchText"
  v-on:input="searchText = $event"
></custom-input>

Vue.component('custom-input', {
   
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
})

有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:
通过 Vue 的 元素加一个特殊的 is attribute 来实现:

<!-- 组件会在 `currentTabComponent` 改变时改变 -->
// currentTabComponent 可以包括
<component v-bind:is="currentTabComponent"></component>
<template>
  <div>
  	<component v-bind:is="currentTabComponent"></component>
    <button @click="changeTab('ComponentA')">Component A</button>
    <button @click="changeTab('ComponentB')">Component B</button>
    <button @click="changeTab('ComponentC')">Component C</button>
  </div>
</template>
<script>
	import ComponentA from './ComponentA.vue';
	import ComponentB from './ComponentB.vue';
	import ComponentC from './ComponentC.vue';
	export default {
   
	  components: {
   
	    ComponentA,
	    ComponentB,
	    ComponentC
	  },
	  data() {
   
	    return {
   
	      currentTabComponent: 'ComponentA'
	    }
	  },
	  methods: {
   
	    changeTab(component) {
   
	      this.currentTabComponent = component;
	    }
	  }
	}
</script>

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2023-12-09 04:32:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-09 04:32:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-09 04:32:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-09 04:32:02       20 阅读

热门阅读

  1. TypeScript中的undefined,void,null

    2023-12-09 04:32:02       34 阅读
  2. C\C++ 获取最值

    2023-12-09 04:32:02       33 阅读
  3. Auth模块的使用

    2023-12-09 04:32:02       33 阅读
  4. 【qml入门系列教程】:qml QtObject用法介绍

    2023-12-09 04:32:02       32 阅读
  5. 【POSTGIS】判定点位是否在范围内

    2023-12-09 04:32:02       34 阅读
  6. 雷军:我的程序人生路

    2023-12-09 04:32:02       35 阅读
  7. leetcode做题笔记1423. 可获得的最大点数

    2023-12-09 04:32:02       35 阅读
  8. mysql 表分区类型

    2023-12-09 04:32:02       38 阅读
  9. 微信小程序保存二维码的过程

    2023-12-09 04:32:02       40 阅读
  10. 策略产品经理常用的ChatGPT通用提示词模板

    2023-12-09 04:32:02       37 阅读
  11. 项目代码规范

    2023-12-09 04:32:02       39 阅读
  12. GUN编译器(gcc/g++)- 编译过程

    2023-12-09 04:32:02       28 阅读
  13. 十年婚姻·总结六

    2023-12-09 04:32:02       43 阅读
  14. 【C++ Primer Plus学习记录】逻辑表达式

    2023-12-09 04:32:02       36 阅读