親子コンポーネント通信がフィボナッチ数列の印刷を実現
効果:
実装コード:
Fibonacci.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件通信之斐波那契数列案例</title>
</head>
<body>
<div id="info">
<showfib :fnums="nums" @fiblist="getflist"></showfib>
<h3>Fibonacci Sequence List</h3>
<p v-for="item in flist">{
{item}}</p>
</div>
<!-- 父组件模板-->
<template id="showfib">
<table cellspacing="0" border="1" cellpadding="20">
<caption style="margin-bottom: 10px;">Fibonacci Sequence(n >= 2)</caption>
<thead>
<tr>
<th v-for="(m, index) in fnums">{
{fname1(index)}}</th>
<th>n</th>
</tr>
<tr>
<th v-for="(m, index) in fnums">{
{fname2(index)}}</th>
<th>{
{n}}</th>
</tr>
</thead>
<tbody>
<tr>
<td v-for="m in fnums">{
{m}}</td>
<td>
<button @click="decrement" :disabled="n <= 2">-</button>
<button @click="increment">+</button>
</td>
</tr>
</tbody>
</table>
</template>
<script src="../../../../js/vue.js"></script>
<script src="Fibonacci.js"></script>
</body>
</html>
Fibonacci.js
// 子组件
let showfib = {
template: `#showfib`,
props: {
fnums: Array,
},
data() {
return {
n: 2,
}
},
computed: {
// 计算属性不能直接传参,若传参则要用闭包函数接收
fname1(){
return function (index) {
let x = 2 - index;
if ( x > 0){
return 'F(n -' + x + ')';
} else {
return 'F(n)';
}
}
},
fname2(){
return function (index) {
return 'F(' + index + ')';
}
}
},
methods: {
decrement(){
if (this.n > 2) {
this.n--;
this.fnums[2] = this.fnums[1];
this.fnums[1] = this.fnums[0];
this.fnums[0] = this.fnums[2] - this.fnums[1];
}
},
increment() {
let newfnum;
this.n++;
this.fnums[0] = this.fnums[1];
this.fnums[1] = this.fnums[2];
this.fnums[2] = this.fnums[0] + this.fnums[1];
newfnum = this.fnums[2];
this.$emit('fiblist', newfnum, this.n);
}
}
}
// vue实例看作父组件
const info = new Vue({
el : "#info",
data : {
nums: [0, 1, 1],
flist: [
'F(0) = 0',
'F(1) = 1',
'F(2) = 1',
],
},
components: {
showfib,
},
methods : {
getflist(newfnum, n){
this.flist .push('F(' + n + ') = ' + newfnum);
}
}
})