0

小白问一个 VueJs 的问题

 1 year ago
source link: https://www.v2ex.com/t/890922
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Vue.js

小白问一个 VueJs 的问题

  honkew · 7 小时 10 分钟前 · 613 次点击

我想这么写 不行

<div v-for="item of list">
<div @click="PromptSetValue(item.it)"></div>


function PromptSetValue(e){
    var text = prompt();
    e = text;
}

需要这么写 才可以

<div v-for="item of list">
<div @click="PromptSetValue(item)"></div>


function PromptSetValue(e){
    var text = prompt();
    e.it = text;
}

有没有什么好办法,因为还需要在其它地方用的这个方法

8 条回复    2022-10-29 16:06:30 +08:00
hay313955795

hay313955795      6 小时 9 分钟前

item.it 传的是一个值...item 给的是一个对象.

PromptSetValue 里循环列表找到对应值的对象改数据呗
TianQian

TianQian      6 小时 6 分钟前

Vue2 没有更好的办法
shintendo

shintendo      5 小时 49 分钟前   ❤️ 2

这跟 Vue 没有任何关系,是编程语言的传值 /传引用问题。

第一种写法,e 是 item.it 的复制品,你给 e 赋值赋出花来也不会影响 item.id

第二种写法,e 是 item 的复制品,但 e.ititem.id 是同一个东西,所以给 e.it 赋值就是给 item.id 赋值。

办法就是用第二种写法。
charlie21

charlie21      4 小时 15 分钟前

PromptSetValue(item.it)

function PromptSetValue (list, it) {
var text = prompt();
foreach (item of list) {
if (it === item.it) { item.it = text; break; }
}
console.log(list) // 确认已更新
}

一种可能性是直接方法名变成 PromptSetValue (list, item.it) 虽然很难看
summerLast

summerLast      3 小时 41 分钟前

和语言无法 第一个地方的 赋值并不是给 上面迭代的 item 进行了赋值, 而是相当于把 item 的引用赋值给了 e ,如果给 e 赋值的话并不会改变原有的 item 可以理解成 a b c 持有一个 item 的引用 赋值的过程给 b 持有了一个新的引用 而非原来的医用如下面例子:
```
a = {it:1};
b = a;
b = {it:2};
```
问此时 a 的值是多少
第二个则是 a b c 持有一个引用,并未对 a b c 修改新的引用 而是通过改引用找到 item 的属性 it 进行了赋值 如下例子
```
a = {it:1};
b = a;
b.it = 2;
```
问此时 a 的值是多少

如果需要改变值可以传入当前元素下标 ,结合数组进行修改 this.$set(list,index,text)

b.id = 1 b 指向 xxx 内存地址,b.it 指向 xxx 内存对应 it 的地址, 给 xxx 指向的 it 地址赋值 为 1
b={id:1} 是指将原有 b 指向的 xxx 内存地址改为指向 新创建对象对应的 yyy 内存地址,而此时 a b 已经没有关系
summerLast

summerLast      3 小时 26 分钟前

两个的本质都是传值(或则叫传引用 /或则叫 copy ),传的是指针对象类型的值( copy ), 指针对象中指向了具体的对象数据和对象类型,还是以上面为例
- 如果直接对变量赋值其含义是修改变量所指向的数据
- 如果对指针对象指向的属性赋值含义是找到指针所指向的对象修改该对象 xx 属性指向的数据 而改对象的指针并会不变

结合上面两条 第一个写法是修改变量所指向的值, 而变量只是容器 ,好比里面放到是身份证号; e 和 item 是两个容器 对 e 容器修改里面的数据(身份证号)并不影响 item 容器里面的值
而第二个是拿着相同的身份证号找到对应的人(如:张三)对他进行涂抹
arnosolo

arnosolo      3 小时 15 分钟前

我一般是这么写的, 标不标准咱也不知道, 反正用是能用.

interface Cat {
name: string;
weight: number;
}

const cats = reactive<Cat[]>([
{
name: 'mimi',
weight: 5,
},
])

function addCatWeight(name: string, weight = 1) {
const cat = cats.find((cat) => cat.name === name);
if(cat) {
cat.weight += weight
}
}

function setFoodSupply(name: string, supply: number) {
cats.find((cat) => cat.name === name)
}

<ul>
<li v-for="cat of cats" :key="cat.name" @click="addCatWeight(cat.name)">
{{ cat.name }}.weight = {{ cat.weight }}
</li>
</ul>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK