要点如下:
input输入框里面,有一个inputValue,需要做成双向数据绑定v-model
怎么找inputValue:input框里面值发生改变,或者input框被点击,会有e.target.value,赋值给inputValue,这里需要在input框添加事件
只有在input框里面才能获取input值的改变
button按钮要做的是,把已经赋值好的inputValue推到数组里面,因为是响应式引用,所以 需要加ref,
inputValue被包着,需要写成inputValue.value
数组有了,li里面的值通过v-for=""循环遍历得到
所有逻辑写在setup里面,写入setup属性,变量,或者方法,都要return出去
<!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>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
// 定义一个应用,并绑定
const app = Vue.createApp({
// setup函数
setup() {
// 引入vue方法
const { ref, reactive } = Vue;
const Arr = reactive([]);
const inputValue = ref("");
// 处理input值发生改变
const handleInputValueChange = (e) => {
inputValue.value = e.target.value;
};
const handleAdd = () => {
// 点击的时候,获取到input的值,并且把input的值推到数组里面去
Arr.push(inputValue.value);
inputValue.value = "";
// 推到数组里面去以后,input框变成空
// ul li里面循环遍历获取到数组里面的值,并响应式的渲染到页面
};
//返回setup里面定义的
return {
handleAdd,
inputValue,
Arr,
handleInputValueChange,
};
},
// 模板
// input输入框里面,有一个inputValue,需要做成双向数据绑定v-model
// 怎么找inputValue:input框里面值发生改变,或者input框被点击,会有e.target.value赋值给inputValue,这里需要在input框添加事件
// 只有在input框里面才能获取input值的改变
// button按钮要做的是,把已经赋值好的inputValue推到数组里面,因为是响应式引用,所以 需要加ref,
// inputValue被包着,需要写成inputValue.value
// 数组有了,li里面的值通过v-for=""循环遍历得到
template: `
<input type="text" v-model="inputValue" @input="handleInputValueChange" />
<button @click="handleAdd">点击</button>
<ul>
<li v-for="(item,index) of Arr" :key="index">第{{index+1}}件事:{{item}}</li>
</ul>
`,
});
const vm = app.mount("#root");
</script>
</html>