我发现这个Vue中命名规范真的有点昏头的
组件名: kebab-case(文档中又说有:使用kebab-case和使用PascalCase这两种),晕了晕了;事件名:不存在任何自动化的大小写转换,而是触发的事件名需要完全匹配监听这个事件所用的名称。因此推荐事件名始终使用 kebab-case;作用:父组件通过Prop向子组件传递数据。
大小写: 在使用DOM中的模板时,camelCase (驼峰命名法) 的 prop 名需要使用其等价的 kebab-case (短横线分隔命名) 命名。 总之,就是prop名称使用驼峰法,在DOM模板中使用短横线分隔命名。
Prop类型: 任何类型的值都可以传给一个prop,假设要让每个 prop 都有指定的值类型,只需以对象形式列出 prop,这些 property 的名称和值分别是 prop 各自的名称和类型。
props: { title: String, likes: Number, isPublished: Boolean, commentIds: Array, author: Object, callback: Function, contactsPromise: Promise // or any other constructor }入门级别demo:
// 子组件: <template> <h3>{{ title }}</h3> </template> <script> export default { name: "article-title", // 注意这里 props: ["title"], }; </script> // 父级组件 <article-title title="小明酱学Vue组件"></article-title> <article-title v-for="post in posts" :key="post.id" :title="post.title"> </article-title>静态传递或者动态传递: 如demo中所示:<article-title title="小明酱学Vue组件"></article-title>是给prop传入一个静态值,或者我们可以通过v-bind对prop进行动态赋值:<article-title v-for="post in posts" :key="post.id" :title="post.title"</article-title>
单向数据流: 所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。 此外,每次父级组件发生变更时,子组件中所有的 prop 都将会刷新为最新的值。
讲点知识点: 父级组件通过v-on监听子组件的任意事件 子组件通过调用内建的$emit方法传入事件名称来触发一个事件,同时可以使用$emit('事件',值)来传入参数,同时在父级组件中使用$event来访问抛出的值。 注意:当事件是一个函数时,这个值会作为第一个参数传入这个方法
<blog-post ... <!--onEnlargeText是一个函数,注意不带括号--!> v-on:enlarge-text="onEnlargeText" ></blog-post> methods: { onEnlargeText: function (enlargeAmount) { this.postFontSize += enlargeAmount } }整个demo 父级组件代码:
// 使用v-on监视字体大小 <div :style="{ fontSize: titleFontSize + 'em'}"> // enlarge-text是子组件在点击按钮后要在父组件中触发的事件,即执行enlargeTitleFontSize()函数 <article-title @enlarge-text="enlargeTitleFontSize()" title="小明酱学Vue组件" ></article-title> </div> methods: { enlargeTitleFontSize() { this.titleFontSize = this.titleFontSize + 0.1; }, },子组件代码:<button @click="$emit("enlarge-text");">Enlarge text</button>
一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,在子组件的<input> 必须:将其 value attribute 绑定到一个名叫 value 的 prop 上,在其 input 事件被触发时,将新的值通过自定义的 input 事件抛出 子组件代码:
<template> <div> <!--关键代码--!> <input :value="value" @input="$emit('input',$event.target.value)" @keyup.enter="printInputText" > </div> </template> <script> export default { name:"custom-input", // 将其 value attribute 绑定到一个名叫 value 的 prop 上 props:["value"], methods: { // 这个方法是我为了显示输入框内容写的,与v-model无关 printInputText(){ this.$emit("print-input-text"); } } } </script>父组件代码:
<!--v-model="inputText" inputText:与输入框中内容绑定的变量--!> <custom-input v-model="inputText" @print-input-text="printInputText" > </custom-input>全局注册我用的很少了,先不写了
// 这是在模块系统进行局部注册 import ComponentA from './ComponentA.vue' export default { components: { ComponentA }, // ... }注意1:在 ES2015+ 中,在对象中放一个类似 ComponentA 的变量名其实是 ComponentA: ComponentA 的缩写,即这个变量名同时是:用在模板中的自定义元素的名称和包含了这个组件选项的变量名。 注意2:使用Babel或者webpack的模块系统时,推荐创建一个 components 目录,并将每个组件放置在其各自的文件中。
这是全局注册基础组件的占位坑(还没用到,但是感觉很有用的,用到在补充,嘻嘻)
以上是我工作中阅读代码遇到的一点问题的总结,还有很多高级的用法没有加上,以后用到在补充叭!