当前位置: 首页 > article >正文

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>

http://www.kler.cn/news/161081.html

相关文章:

  • <习题集><LeetCode><链表><2/19/21/23/24>
  • 每日一练2023.12.7—— 情人节【PTA】
  • 某60区块链安全之薅羊毛攻击实战一学习记录
  • 【C语言】程序设计加密解密
  • mac M系列芯片安装chatGLM3-6b模型
  • js vue 输入正确手机号/邮箱后,激活“发送验证码”按钮
  • 详解线段树
  • C语言——指针的运算
  • LLM(五)| Gemini:谷歌发布碾压GPT-4最强原生多模态,语言理解能力首次超过人类
  • Java API接口强势对接:构建高效稳定的系统集成方案
  • java-HashMap、TreeMap、LinkedHashMap、ArrayList、LinkedList使用笔记
  • 什么是https 加密协议?https证书安装部署
  • 微信小程序复制功能
  • 如何通过内网穿透实现无公网IP也能远程访问内网的宝塔面板
  • C# WPF上位机开发(抽奖软件)
  • 【云原生系列】Kubernetes知识点
  • Python-字典详解
  • 一个简单的参数帮助框架,c实现
  • Android 架构实战MVI进阶
  • Vue3的watch函数中,第三个参数配置对象详细分析
  • uniapp横向滚动示例
  • JavaSE语法之五:数组的定义与使用(超详解!!!)
  • Android12之MediaCodec硬编解码调试手段(四十九)
  • python基于ModBusTCP服务端的业务实现特定的client
  • 反钓鱼防盗号,共筑校园安全防线!Coremail出席CERNET学术年会
  • 案例054:基于微信的追星小程序
  • 代码随想录算法训练营第四十二天 _ 动态规划_01背包问题、416.分割等和子集。
  • 医院有HIS系统,为什么还要开发预约挂号小程序?数据如何互通?
  • 前端笔记(三)CSS 盒子模型
  • ★538. 把二叉搜索树转换为累加树