在做课设的时候,动态生成表格需要写一堆js代码,于是乎决定采用一个前端框架来简化编码过程,之前已经学过Vue的一些知识了,因此直接从组件开始记录。
<div class="vue">
<button-counter>button-counter>
div>
body>
<script>
Vue.component('button-counter',{
data: function () {
return{
count: 0
}
},
template: ""
})
var app = new Vue({
el: '.vue'
})
script>
对比直接写一个button
<div class="vue">
<button-counter>button-counter>
<button>{{count}}button>
div>
<script>
var app = new Vue({
el: '.vue',
data: {
count: 1
}
})
script>
可以看出二者在绑定数据时不同,根据我的理解,当时用component时是创建一个组件的构造器,也就是说每次使用它生成组件各个组件都是独立的,所以它内部的数据是局部数据,需要用function封装起来
<div class="vue">
<button-counter>button-counter>
div>
body>
<script>
Vue.component('button-counter',{
data: function () {
return{
count: 0
}
},
template: "",
methods: {
click: function () {
this.count++
}
}
})
var app = new Vue({
el: '.vue',
})
script>
组件通过methods绑定需要用到的函数
<blog-post title="en">blog-post>
<blog-post title="ene">blog-post>
<blog-post title="enee">blog-post>
Vue.component('blog-post', {
template: "<h3>{{title}}h3>",
props: ['title']
})
在使用组件时可以通过title属性传递给template中的{{title}}
来看一个复杂的栗子
//html
post v-for="post in posts" v-bind:post="post"> post>
//js
Vue.component('blog-post', {
template: "{{post.id}}{{post.title}}",
props: ['post'],
})
var app = new Vue({
el: '.vue',
data: {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
]
}
})
首先看html中,我们把暂时当做一个普通的标签,使用v-for标签遍历app中的posts(因为他在el:‘.vue’下,所以可以得到值),接下来把遍历来的post的值绑定到标签的属性post上,同时由于for循环生成了多个标签,相当于此时是这样的:
post post='posts[0]'> post>
post post='posts[1]'> post>
post post='posts[2]'> post>
接下来我们看一下模板
Vue.component('blog-post', {
template: "<div>{{post.id}}{{post.title}}div>",
props: ['post'],
})
这里通过props指定用post属性向模板传值,也就是说此时吧标签翻译成了
<div>{{post[0].id}}{{post[0].title}}div>
<div>{{post[1].id}}{{post[1].title}}div>
<div>{{post[2].id}}{{post[2].title}}div>
为了便于区分,我们把一些post重命名试试,并加入一些东西生成一个完整的博客组件
post v-for="post in posts" v-bind:data="post"> post>
Vue.component('blog-post', {
template: "" +
"第{{data.id}}篇" +
"{{data.title}}
" +
"{{data.content}}" +
"
" +
"",
props: ['data'],
})
var app = new Vue({
el: '.vue',
data: {
posts: [
{ id: 1, title: 'My journey with Vue', content: 'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools' },
{ id: 2, title: 'Blogging with Vue' , content: 'You are running Vue in development mode.\n' +
'Make sure to turn on production mode when deploying for production.\n' +
'See more tips at https://vuejs.org/guide/deployment.html'},
{ id: 3, title: 'Why Vue is so fun', content: 'component lists rendered with v-for should have explicit keys. See https://vuejs.\n' +
'org/guide/list.html#key for more info.\n' }
]
}
})
现在有个需求,我希望可以点击按钮查看某个博文的详细信息,在js可以直接用闭包实现,我们来看看Vue