vue

setup

Posted by アライさん on 2022年08月12日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//temp1相关代码写在一起
const temp1 = function(){
//数据项
const data1 = reactive({})
//计算属性
const count1 = computed(()=>{})
//操作
const func1 = ()={}

return {data1,count1,func1}
}

//temp2相关代码写在一起
const temp2 = function(){
const data2 = reactive({})
const count2 = computed(()=>{})
const func2 = ()={}
return {data2,count2,func2}
}

//setup整合temp1、temp2
new Vue({

data(){}

setup(){
const { data1,count1,func1 } = temp1()

const { data2,count2,func2 } = temp2()

return { data1,count1,func1,data2,count2,func2 }
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!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>用户列表</title>
<script src="https://unpkg.com/vue@next"></script>
<style>
.container{
margin: 50px;
}
.content{
margin: 20px;
}
</style>
</head>
<body>
<div id="Application"></div>
<script>
//数据
let mock = [
{
name:'小王',
sex:0,
},
{
name:'小红',
sex:1,
},
{
name:'小李',
sex:0,
},
{
name:'小张',
sex:1,
},
];
const App = Vue.createApp({
setup(){
const showDatas = Vue.ref([]);
//延迟3秒填充数据
const queryAllData = () => {
setTimeout(() => {
showDatas.value = mock
}, 3000);
};
//挂载之后执行queryAllData
Vue.onMounted(queryAllData);
let sexFilter = Vue.ref(-1);
let searchKey = Vue.ref("");

//筛选性别
let FilterData = ()=>{
searchKey.value = "";
if(sexFilter.value == -1){
showDatas.value = mock;
}else{
showDatas.value = mock.filter((data)=>{
return data.sex == sexFilter.value;
});
}
};
//搜索数据
let searchData = ()=>{
sexFilter.value = -1;
if(searchKey.value.length == 0){
showDatas.value = mock;
}else{
showDatas.value = mock.filter((data)=>{
return data.name.search(searchKey.value) != -1;
});
}
};
//挂载watch
Vue.watch(sexFilter,FilterData);
Vue.watch(searchKey,searchData);
return {
showDatas,
searchKey,
sexFilter,
};
},

template:`
<div class="container">
<div class="content">
<input type="radio" v-bind:value="-1" v-model="sexFilter"/>全部
<input type="radio" v-bind:value="0" v-model="sexFilter"/>
<input type="radio" v-bind:value="1" v-model="sexFilter"/>
</div>

<div class="content">搜索:<input type="text" v-model="searchKey" /></div>

<div class="content">
<table border="1" width="300px">
<tr>
<th>姓名</th>
<th>性别</th>
</tr>
<tr v-for="(data,index) in showDatas" >
<td>{{data.name}}</td>
<td>{{data.sex == 0?'男':'女'}}</td>
</tr>
</table>
</div>
</div>
`,
});
App.mount("#Application");
</script>
</body>
</html>