首页 > 解决方案 > Vue中如何放变量

问题描述

我正在学习 vue,我有一个小问题。

我创建了代码,它从 webserwer (通过套接字)接收一些信息,并且该代码工作正常。

但我想做非常简单的事情——在 HTML 中将信息显示为变量,但我遇到了问题。

我的代码是:

    export default {
  components: {
    BCard,
    BButton,
  },
  data() {
    return {
      connection: null,
      json: {
        cmd: 'start',
        width: 1024,
        height: 800,
        url: 'https://www.google.com',
        token: '',
        service_id: 1,
        thumbnail_width: 100,
        thumbnail_height: 100,
      },
    }
  },
  created() {
    console.log('Starting Connection to WebSocket')
    this.connection = new WebSocket('ws://127.0.0.1:8080/')
    // this.connection = new WebSocket('ws://echo.websocket.org')
    this.connection.onopen = function (event) {
      console.log(event)
      console.log('Success')
    }
    this.connection.onmessage = webSocketOnMSG
  },
  methods: {
    sendMessage(message) {
      console.log(this.connection)
      console.log(message)
      console.log(JSON.stringify(message))
      const dat = this.connection.send(JSON.stringify(message))
      console.log('TT', dat)
    },
    drawItem() {
      const img = document.createElement('img')
      const canvas = document.getElementById('canvasId')
      img.src = 'http://image...'
      img.onload = function (a) {
        const h = a.target.height
        const w = a.target.width
        const c = canvas.getContext('2d')
        canvas.width = w
        canvas.height = h
        c.drawImage(img, 0, 0)
        document.getElementById('draw-image-test').appendChild(canvas)
      }
    },
    webSocketOnMSG(msg) {
      console.log(msg)
    },
  },
}

我想添加这样的代码:

data: {
xposition: 'xpos',
yposition: 'ypos'
}

但是当我将它添加到之前创建的时data()我有错误,所以这不起作用:

data() {
xposition: 'xpos',
yposition: 'ypos',
        return {...}
}

我应该在哪里添加代码来替换 HMTL 中的变量 {{xposition}} 和 {{yposition}}?

标签: javascriptvue.js

解决方案


您必须将新变量放在数据函数中返回的对象中,与您的“json”变量一起。您需要先将它们声明为空值,然后在 API 调用回调中添加正确的值

data() {
  return {
    xposition: '',
    yposition: '',
    ...
  }
}

    webSocketOnMSG(msg) {
      // this will change your component's xposition property
      this.xposition = msg.propertyYouWantToAccess
    },


推荐阅读