我创建了一个完整的Rails应用程序,但我添加了<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
a.k.a. Vue框架,仅用于处理一些特定的任务。这些任务之一是像这样控制范围输入组件:
_ a_single_layout.html.erb
<div id="app">
<h1>{{progress}}%</h1>
<input type="range" min="0" max="100" v-model="progress">
</div>
application.js
let app = new Vue({
el: "#app",
data: {
progress: 0
}
})
我得到的是:
问题是如何在此处从Rails应用程序中设置当前存储的值,并同时将此值绑定到Vue模型。
我尝试过的事情:
<h1>{{progress = <%= @model.progress %>}}%</h1>
●这实际上就是我想要的值,但是范围输入卡住了。
<input type="range" min="0" max="100" v-bind:progress="<%= @model.progress %>">
●这会将范围移动到其预期位置,但是当我用鼠标移动它时将停止刷新视图。
<input type="range" v-model="progress" v-bind:progress="<%= @model.progress %>">
●同时设置v-model
和v-bind
将忽略最后一个。
let app = new Vue({
el: "#app",
data: {
progress: <%= @model.progress %>
}
})
●另外,我也尝试在javascript端编写值,但这不是rails的有效语法。
●我正在寻找类似v-on:load="progress = <%= @model.progress %>"
的东西,但似乎v-on没有任何加载事件处理程序。
以下是我在笔上尝试过的东西:https://codepen.io/alex3o0/pen/XWrLwwm
我只是采用了一种棘手的解决方案;我将rails模型变量设置为Vue模型变量,直到“卡住”,但是在创建的方法上(使用setTimeout延迟动作¯\ _(ツ)_ /¯),我将此值重新分配给了第二个完全免费的Vue模型变量:
_ a_single_layout.html.erb
<div id="app">
<span class="hide-me">{{real_value = <%= @model.progress %>}}</span><!-- this variable gets the value from the rails model but also gets "stuck" -->
<h1>{{progress}}%</h1>
<input type="range" min="0" max="100" v-model="progress"><!-- this variable will get its real value when the "created" method starts -->
</div>
application.js
let app = new Vue({
el: "#app",
data: {
progress: 0,
real_value: 0
},
created: function(){
setTimeout(() => this.progress = this.real_value, 1000)
}
})
顺便说一句,我仍然在寻找“正确的”解决方案。
解决方案是创建Vue组件。然后,您可以使用props通过此组件将“ rails”数据传递到Vue。您只需要先将其转换为JSON:
_ a_single_layout.html.erb
<div id="app">
<load-progress :progress="<%= @model.progress.to_json %>"></load-progress>
</div>
application.js
const LoadProgress = Vue.component('load-progress', {
template: `
<div>
<p>{{ progress }}%</p>
<input type="range" min="0" max="100" :value="progress">
</div>`,
props: ['progress']
})
const app = new Vue({
el: '#app',
components: { LoadProgress }
})