如何在 javascript 和 Vue 中动态设置图像对象 src

How to dynamically set an Image object src in javascript and Vue

我正在努力自学 javascript 和 Vue.js。我一直在关注 Vue 网站上的文档,并将他们的演示修改为练习。我想更改他们的循环指令示例,以将图像从指定的 url 动态添加到列表中。尽管设置了图像属性 src 字段,但我似乎无法显示图像。我已经验证一切都在运行,并且该字段实际上正在设置。我想我一定是误解了与 DOM 或事件顺序相关的内容。

提前致谢。

HTML

<script src="https://unpkg.com/vue@next"></script>

<div id="list-rendering" class="demo">
  <input v-model="imgsrc"></input>
  <button v-on:click="setImage">  Set</button>
  <ol>
    <li v-for="todo in todos">
      {{ todo.text }} {{todo.image}}
    </li>
  </ol>
</div>

CSS

.demo {
  font-family: sans-serif;
  border: 1px solid #eee;
  border-radius: 2px;
  padding: 20px 30px;
  margin-top: 1em;
  margin-bottom: 40px;
  user-select: none;
  overflow-x: auto;
}

Javascript

const ListRenderingApp = {
  data() {
    return {
      todos: [
        { text: 'Learn JavaScript',
          image: new Image(16,16)},
        { text: 'Learn Vue',
          image: new Image(16, 16)},
        { text: 'Build something awesome',
          image: new Image(16, 16)}
      ],
      imgsrc: ""
    }
  },
  methods:{
    setImage(){
       this.todos.map(todo => todo.image.src = this.imgsrc)
    }
  }
}

Vue.createApp(ListRenderingApp).mount('#list-rendering')
try this.   

<div id="list-rendering" class="demo">
      <input v-model="imgsrc"></input>
      <button v-on:click="setImage">  Set</button>
      <ol>
        <li v-for="(todo, index) in todos :key="index"">
          {{ todo.text }} 
          <img :src="todo.image"/>
        </li>
      </ol>
    </div>

使用 v-for 时务必添加 :keyDocs

还要注意您的 html 要素。 <img> & <input>.

还有return.map()this.todos的结果。 Docs

new Vue({
  el: "#app",
  data: {
    imgSrc: 'https://via.placeholder.com/150/FF0000',
    todos: [
      { text: "Learn JavaScript", image: 'https://via.placeholder.com/150/0000FF' },
      { text: "Learn Vue", image: 'https://via.placeholder.com/150/0000FF' },
      { text: "Play around in JSFiddle", image: 'https://via.placeholder.com/150/0000FF' },
      { text: "Build something awesome", image: 'https://via.placeholder.com/150/0000FF' }
    ]
  },
  methods: {
    setImage: function(todo){
        this.todos = this.todos.map(todo => ({ ...todo, image: this.imgSrc }))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <small>image url</small>
    <input v-model="imgSrc" />
  </div>
  <br />
  <div>
    <button @click="setImage()">
      Click to set Image
    </button>
  </div>
  <ol>
    <li v-for="(todo, i) in todos" :key="i">
      <label>
          {{ todo.text }}
      </label>
      <img :src="todo.image" alt="img" width="100" height="100">
    </li>
  </ol>
</div>

尝试 运行 此代码段并单击“单击以设置图像”