网站开发语言分类,家具设计与工程就业前景,wordpress谷歌字体加载慢,免费商标logo在线制作软件1、组件的定义
一般将 Vue 组件定义在一个单独的 .vue 文件中#xff0c;称做单文件组件#xff1b;当然也可以将组件直接定义在js文件中#xff0c;如下js代码#xff0c;定义一个组件BlogPost#xff0c;通过props定义对外暴露属性title#xff0c;父组件传递title称做单文件组件当然也可以将组件直接定义在js文件中如下js代码定义一个组件BlogPost通过props定义对外暴露属性title父组件传递title子组件根据title渲染html内容。
export default {props: [title],template: div classblog-posth4{{ title }}/h4/div
}
2、组件的使用
首先需要引用组件语法格式import BlogPost from ./BlogPost.js然后在vue应用对象中注册组件在components区域注册即可最后在DOM元素内部使用标签格式如代码blog-post titleMy jouney with Vue/blog-post应用子组件并传递title属性给子组件渲染。
script srchttps://unpkg.com/vue3/dist/vue.global.js/script
div idappblog-post titleMy jouney with Vue/blog-post
/div
script typemoduleimport BlogPost from ./BlogPost.jsconst { createApp } Vue;createApp({components: {BlogPost},}).mount(#app);
/script
3、组件的重复应用
可以使用v-for语法循环创建子组件如代码所示
script srchttps://unpkg.com/vue3/dist/vue.global.js/script
div idappblog-post v-forpost in posts :keypost.id :titlepost.title/blog-post
/div
script typemoduleimport BlogPost from ./BlogPost.jsconst { createApp } Vue;createApp({data() {return {posts: [{ id: 1, title: My jounery with Vue },{ id: 2, title: Blogging with Vue },{ id: 3, title: Why Vue is so fun }]}},components: {BlogPost}}).mount(#app);
/script
4、给组件传递事件
组件中模板声明一个按钮并使用click绑定点击事件使用$emit抛出一个事件名为enlarge-text并通过emits定义对外抛出的事件名称enlarge-text定义如下代码所示
export default {props: [title],emits: [enlarge-text],template: div classblog-posth4{{ title }}/h4button click$emit(enlarge-text)Enlarge text/button/div
}
应用组件应用中定义字体大小属性postFontSize在组件blog-post应用的代码处定义事件enlarge-textpostFontSize0.1点击后触发字体0.1
script srchttps://unpkg.com/vue3/dist/vue.global.js/script
div idappdiv :style{ fontSize: postFontSize em }blog-post v-forpost in posts :keypost.id :titlepost.title enlarge-textpostFontSize0.1/blog-post/div
/div
script typemoduleimport BlogPost from ./BlogPost.jsconst { createApp } Vue;createApp({data() {return {posts: [{ id: 1, title: My jounery with Vue },{ id: 2, title: Blogging with Vue },{ id: 3, title: Why Vue is so fun }],postFontSize:1}},components: {BlogPost},mounted() {}}).mount(#app);
/script
5、插槽的应用
在组件中定义一个插槽模板中语法slot/
export default {template: div classalert-boxstrongThis is an Error for Demo Purpose/strongslot//div
}
在vue应用中给插槽传递html内容alert-box元素中的内容“Something bad happened.”将传递给组件的插槽
script srchttps://unpkg.com/vue3/dist/vue.global.js/script
div idappalert-boxSomething bad happened./alert-boxtabletrtd123/tdtd456/td/trtr isvue:alert-box/tr/table
/div
script typemoduleimport AlertBox from ./AlertBox.jsconst { createApp } Vue;createApp({data() {return {}},components: {AlertBox}}).mount(#app);
/script