javascript - 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}}?
解决方案
您必须将新变量放在数据函数中返回的对象中,与您的“json”变量一起。您需要先将它们声明为空值,然后在 API 调用回调中添加正确的值
data() {
return {
xposition: '',
yposition: '',
...
}
}
webSocketOnMSG(msg) {
// this will change your component's xposition property
this.xposition = msg.propertyYouWantToAccess
},
推荐阅读
- apache-kafka - 消息流已修改 (41) 或 kafka 客户端超时
- c++ - C++ 快速文件逐行读取
- jquery - 当我放一个 href 时,jQuery 导航栏中的活动类不起作用
- powershell - 比较两个 csv 文件,在 powershell 中缺少预期结果
- java - Oauth2 刷新令牌
- reactjs - 调用 Jest 模拟函数。但是模拟的状态没有更新?
- java - 如何在java中制作待办事项列表?
- azure - 在 Microsoft Graph 中检索每个应用程序的角色和用户
- java - 在 Socket.io-client 中发送自定义标头
- vsto - 使用 MSI 安装程序(通过 Wix 生成)后无法更改 Word AddIn 的 VSTO appSettings