【Vue.js 入门到实战教程】06-在 Vue.js 中通过计算属性动态设置属性值
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性示例代码title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js">script>
<style>
.php {
color: cornflowerblue;
}
.javascript {
color: gold;
}
.golang {
color: aqua;
}
.python {
color: darkgreen;
}
style>
head>
<body>
<div id="app">
<p>Web开发框架:p>
<ul>
<li v-for="framework in frameworks" :class="framework.language">
{{ framework.name }}
li>
ul>
<hr>
框架:<input v-model="newFramework" name="framework"/>
语言:
<select v-model="newLanguage">
<option v-for="language in languages" v-text="language">option>
select>
<button @click="addFramework">新增框架button>
div>
<script>
var app = new Vue({
el: '#app',
data: {
frameworks: [
{'name': 'Laravel', 'language': 'php'},
{'name': 'Vue', 'language': 'javascript'},
{'name': 'Gin', 'language': 'golang'},
{'name': 'Flask', 'language': 'python'},
],
languages: [
'php', 'golang', 'javascript', 'python'
],
newFramework: '',
newLanguage: '',
},
methods: {
addFramework() {
this.frameworks.push(
{'name': this.newFramework, 'language': this.newLanguage}
);
}
}
});
script>
body>
html>
排序函数
methods: {
addFramework() {
this.frameworks.push(
{'name': this.newFramework, 'language': this.newLanguage}
);
// 对 frameworks 数组按照 language 字段做升序排序
this.frameworks.sort((a, b) => {
if (a.language < b.language) {
return -1;
} else if (a.language > b.language) {
return 1;
} else {
return 0;
}
});
}
}
计算属性
methods: {
addFramework() {
this.frameworks.push(
{'name': this.newFramework, 'language': this.newLanguage}
);
}
},
computed: {
// 定义一个计算属性 sortedFrameworks
sortedFrameworks() {
return this.frameworks.sort((a, b) => {
if (a.language < b.language) {
return -1;
} else if (a.language > b.language) {
return 1;
} else {
return 0;
}
});
}
}
{{ framework.name }}
评论