Passing data from PHP/HTML to .vue Component

喜欢而已 提交于 2021-02-19 05:18:06

问题


What I'm trying to do is seemingly simple, but I can't seem to figure it out. Basically, I have 2 files:

A PHP file with the following:

...
<user-panel v-if="user.id  && loaded" v-bind:user="user" v-bind:name="theUserName"></user-panel>
...

A .Vue component file with the following (that gets compiled into another file):

<template>
    <span id="userPanel" class="d-flex align-items-center">
        <a href="#" role="button" class="user-dropdown-toggle">
            <div class="logged-in d-flex align-items-center">
                <span class="d-flex align-items-center justify-contnet-center"></span>
                {{name}}
            </div>
        </a>
    </span>
</template>

<script>
    export default {
        name: "UserPanel",
        props: ['user'],
        created () {
            console.log(this.$refs.myTestField.value)
        }
    }
</script>

All I'd like to do is pass data from the PHP to Vue into {{name}}. I've tried v-bind, a data-attribute, a hidden input, etc. Any help would be greatly appreciated.


回答1:


Vue single file components are processed on client side.

There are SSR, however, since you have php on your server, you must set up a REST service so you can use fetch or axios to consume server data and present it to the client side.




回答2:


Let's say you have a php variable that contains string. $phpString

PHP file

...
<my-component v-bind:myProperty="<?php echo $phpString ?>"></my-component>
...

Don't forget to escape $phpString before echoing it.

In your Vue define a property called myProperty:

<template>
  <span>
    {{ myProperty }}
  </span>
</template>

<script>
export default {
  props: ['myProperty']
}
</script>



回答3:


My intention is to transfer data from my .php file to the .js file where the VUE code resides. Here I show you my code. In the proposed example I would like to import a simple string, subsequently I would like to import a JSON. Thank you so much. File PHP

<div id='app'> <App v-bind:import='Value Import'> C'è QUALCHE PROBLEMA </App> </div>"

File .js

var App = Vue.component("App", {
    template: `
      <div class="container">
        <div>
          <h2>{{ titolo }}</h2>
          <h3>{{ import }}</h3>

        </div>
      </div>
    `,
    props: ['import'],

    data() {
      return {
        color: "color: red",
        titolo: "Inizio Container",
      };
    }
  });

  new Vue({
    el: "#app",
  });

Quanto sopra purtroppo non funziona.



来源:https://stackoverflow.com/questions/54048767/passing-data-from-php-html-to-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!