官方说明:
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.main {
width: 500px;
border: 1px solid #ccc;
margin: 10px 0;
padding: 10px 10px;
}
.title {
font-size: 36px;
}
.content {
font-size: 22px;
}
input {
padding: 5px 0;
margin: 10px 0 0;
}
</style>
</head>
<body>
<div id="app">
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script src="../node_modules/loadsh/lodash.js"></script>
<script>
Vue.component('my-com', {
template:`
<div class="main">
<div class="title"> {{ obj.name }} </div>
<div class="content"> {{ obj.name }} </div>
<input type="text" placeholder="请输入备注">
</div>
`,
props: ['obj']
});
var App = {
data() {
return {
items: [
{id:1, name: 'banana'},
{id:2, name: 'apple'},
{id:3, name: 'watermelon'}
]
}
},
template:`
<div>
<button @click="changeSort">改变顺序</button>
<!-- :key='item.id'数据库中有返回id就用id,没有就用index 如果没有key会导致代码紊乱 -->
<!-- 当给组件使用 v-for 遍历的时候,一定要加上 :key 属性,通过key值来提升渲染的效率 -->
<my-com v-for="(item, index) in items" :obj="item" ></my-com>
</div>
`,
methods: {
changeSort() {
console.log(1);
this.items = _.shuffle(this.items); // _.shuffle创建一个被打乱值的集合
}
}
};
new Vue({
el: '#app',
components: {
App
},
template:`
<App />
`
});
</script>
</body>
</html>
这里用到了loadsh中的_.shuffle集合,需要下载安装开发依赖loadsh:
cnpm i loadsh -D
_.shuffle集合的作用是:创建一个被打乱值的集合。
实现效果: