【问题标题】:Set value to Vue model from rails rendering process从 rails 渲染过程为 Vue 模型设置值
【发布时间】:2019-10-01 17:12:15
【问题描述】:

我创建了一个完整的 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-modelv-bind 会忽略最后一个。

let app = new Vue({
  el: "#app",
  data: {
    progress: <%= @model.progress %>
  }
})

● 我也尝试在 javascript 端写入值,但这不是 rails 的有效语法。

● 我正在寻找类似v-on:load="progress = &lt;%= @model.progress %&gt;" 的东西,但似乎 v-on 没有任何加载事件处理程序。

这是我在笔上试过的东西:https://codepen.io/alex3o0/pen/XWrLwwm

【问题讨论】:

    标签: ruby-on-rails vue.js erb


    【解决方案1】:

    我只是采用一种棘手的解决方案;我将我的 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)
      }
    })
    

    顺便说一句,我还在寻找“正确”的解决方案。

    【讨论】:

      【解决方案2】:

      解决方案是创建一个 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 }
      })
      

      【讨论】:

        猜你喜欢
        • 2010-11-18
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        • 2019-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多