Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:得抓紧时间了
const childComponent = Vue.extend({
template: `<h2>Hello Wrold</h2>`,
});
Vue.component("child-component", childComponent);
const vm = new Vue({
el: "#root",
});
可将第一、二步省略,简写为:Vue.component(组件名,对象字面量表示的组件配置项);再进行第三步挂载,可以达到同样的效果。
Vue.component("child-component", {
template: `<h2>Hello Wrold</h2>`,
});
HTML代码
<div id="root">
<child-component></child-component>
<child-component></child-component>
</div>
<div id="root">
<button-inc></button-inc>
</div>
Vue.component("button-inc", {
template: `
<div>
<button @click="count++">点赞: + {{count}}</button>
</div>
`,
data() {
return {
count: 0,
};
},
});
const vm = new Vue({
el: "#root",
});
Vue.component("button-inc", {
template: "#inc",
data() {
return {
count: 0,
};
},
});
HTML代码
<div id="root">
<button-inc></button-inc>
</div>
<template id="inc">
<div>
<button @click="count++">点赞: + {{count}}</button>
</div>
</template>
<div id="root">
<hellos></hellos>
</div>
<template id="hello">
<p>Hello2 {{site}}</p>
</template>
const hellos = {
template: '#hello',
data() {
return {
site: "php中文网",
};
},
};
const vm = new Vue({
// el: "#root",//可将此步用后面.$mount("#root")代替
components: { hellos },
}).$mount("#root");
<div id="app">
<btn-inc :my-name="username" :my-count="count"><btn-inc>
</div>
const vm = new Vue({
el: document.querySelector("#app"),
data() {
return {
username: "有声的紫荆",
count: 0,
};
},
// 局部组件
//组件之间的数据传递是单向的,不允许在子组件中更新父组件中的数据
components: {
btnInc: {
props: ["myName", "myCount"],
template: `
<div>
<button @click="num++">点赞: + {{num}}</button>
<span>{{myName}}</span>
</div>
`,
data() {
return {
num: this.myCount,
};
},
},
},
});
<div id="app">
<btn-inc :my-name="username" :my-count="count" @click-count="handle"></btn-inc>
</div>
const vm = new Vue({
el: document.querySelector("#app"),
data() {
return {
username: "有声的紫荆",
count: 0,
};
},
// 局部组件
components: {
btnInc: {
props: ["myName", "myCount"],
template: `
<div>
<button @click="$emit('click-count',10 )">点赞: + {{myCount}}</button>
<span>{{myName}}</span>
</div>
`,
},
},
// 父组件更新数据的方法
methods: {
handle(value) {
this.count += value;
this.username = "天蓬老师";
},
},
});
<div id="app">
<p>父组件: {{price}} 元</p>
<p>
<span>子组件:</span>
<my-input :my-price="price" @input-text="handle"></my-input> 元
</p>
</div>
const vm = new Vue({
el: document.querySelector("#app"),
data() {
return {
price: 4588,
};
},
// 局部组件
components: {
"my-input": {
props: ["my-price"],
template: `
<input type="text" :value="myPrice" @input="foo" />
`,
methods: {
foo(ev) {
this.$emit("input-text", ev.target.value);
},
},
},
},
methods: {
handle(value) {
this.price = value;
},
},
});
<slot></slot>
)
<div id="app">
<my-comp>Wrold</my-comp>
</div>
new Vue({
el: "#app",
components: {
myComp: {
template: `
<div>
<h2>Hello <slot>哈哈哈</slot> </h2>
</div>
`,
},
},
});
//其中“哈哈哈”为默认值,当`<my-comp></my-comp>`之间无内容时,将会把默认值显示出来。