1

Estou iniciando no Vue.js e agora estou em um momento que não consigo fazer. Preciso por exemplo conectar no PHP e fazer um select no MySQL pra trazer uns dados. Porém não sei como proceder no Vue.js, vou colocar o código aqui.

Tentei fazer assim atraves de um tutorial da internet mas acho que não deu certo.

Meu PHP:

<?php

$conn = mysql_connect("127.0.0.1","root","");
$db   = mysql_select_db("techall14");

$sql = mysql_query("SELECT * FROM estoque_filial");

$i = 0;
while ($resposta = mysql_fetch_array($sql))
{

    $ret[$i]["Id"]=$resposta['Id'];
    $ret[$i]["filial"]=$resposta['filial'];
    $ret[$i]["descricao"]=$resposta['descricao'];
    
    $ano = substr($resposta['data_cad'],0,4);
    $mes = substr($resposta['data_cad'],5,2); 
    $dia = substr($resposta['data_cad'],8,2); 
    $data_cad = $dia."/".$mes."/".$ano;
    
    $ret[$i]["data_cad"]=$data_cad;
    $ret[$i]["operador"]=$resposta['operador'];
    $ret[$i]["status"]=$resposta['status'];
$i ++;

}

header("Content-type: application/json");
echo json_encode($ret);
        
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vue2</title>
    <script src="vueJS/vue.min.js"></script>
    
  </head>
  <body>
    <div id="root">
        <table border="1" cellpadding="0" cellspacing="0" >
            <tr>
                <th width="162">Teste (1)</th>
                <th width="144">Teste (2)</th>
                <th width="124">Teste (3)</th>
                <th width="120">Teste (4)</th>
            </tr>
            <tr v-for="user in users">
                <th>{{user.filial}}</th>
                <th>sadasd</th>
                <th>asda</th>
                <th>asda</th>
            </tr>
        </table>
    </div>
    <script>
        new Vue({
          el: '#root',
          data:{
                  users: [],
                newUser:{ username: "", email:""}
             },
             mounted: function(){
                console.log("mounted");
                this.getAllUsers();
            },
            
            methods:{
            
                getAllUsers: function(){
                    
                    axios.get("http://127.0.0.1/VUEJS/teste.php")
                    .then(function(response){
                        console.log(response);
                        if(response.data.error){
                            app.errorMessage = response.date.message;    
                        }else{
                            app.users = response.data.users
                        }    
                        
                    });
                
                    
                }    
                
            }
            
            
        })
    </script>
  </body>
</html>

<?php

$conn = mysql_connect("127.0.0.1","root","");
$db   = mysql_select_db("techall14");

$sql = mysql_query("SELECT * FROM estoque_filial");

$i = 0;
while ($resposta = mysql_fetch_array($sql))
{

    $ret[$i]["Id"]=$resposta['Id'];
    $ret[$i]["filial"]=$resposta['filial'];
    $ret[$i]["descricao"]=$resposta['descricao'];

    $ano = substr($resposta['data_cad'],0,4);
    $mes = substr($resposta['data_cad'],5,2); 
    $dia = substr($resposta['data_cad'],8,2); 
    $data_cad = $dia."/".$mes."/".$ano;

    $ret[$i]["data_cad"]=$data_cad;
    $ret[$i]["operador"]=$resposta['operador'];
    $ret[$i]["status"]=$resposta['status'];
$i ++;

}

header("Content-type: application/json");
echo json_encode($ret);

?>

Meu HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vue2</title>
    <script src="vueJS/vue.min.js"></script>

  </head>
  <body>
    <div id="root">
        <table border="1" cellpadding="0" cellspacing="0" >
            <tr>
                <th width="162">Teste (1)</th>
                <th width="144">Teste (2)</th>
                <th width="124">Teste (3)</th>
                <th width="120">Teste (4)</th>
            </tr>
            <tr v-for="user in users">
                <th>{{user.filial}}</th>
                <th>sadasd</th>
                <th>asda</th>
                <th>asda</th>
            </tr>
        </table>
    </div>
    <script>
        new Vue({
          el: '#root',
          data:{
                  users: [],
                newUser:{ username: "", email:""}
             },
             mounted: function(){
                console.log("mounted");
                this.getAllUsers();
            },

            methods:{

                getAllUsers: function(){

                    axios.get("http://127.0.0.1/VUEJS/teste.php")
                    .then(function(response){
                        console.log(response);
                        if(response.data.error){
                            app.errorMessage = response.date.message;    
                        }else{
                            app.users = response.data.users
                        }    

                    });


                }    

            }


        })
    </script>
  </body>
</html>

1 Resposta 1

1

O seu erro está sendo em utilizar a variável app. Ela não representa nada no seu código. Para alimentar os dados de users, você deve utilizar this.users ou, no caso de estar dentro de outro contexto, armazene o this, e depois utilize a variavel + users. Exemplo de como ficaria seu código da forma correta:

new Vue({
  el: '#root',
  data: {
    users: [],
    newUser: {
      username: "",
      email: ""
    },
    errorMessage: ""
  },
  mounted: function() {
    console.log("mounted");
    this.getAllUsers();
  },

  methods: {

    getAllUsers: function() {

      var self = this; // Armazena a instância do Vue em self

      axios.get("http://127.0.0.1/VUEJS/teste.php")
        .then(function(response) {
          console.log(response);
          if (response.data.error) {
            self.errorMessage = response.date.message;
          } else {
            // Faz referência a data.users
            self.users = response.data.users;
          }
        });
    }
  }

})

1
  • Bruno, muito grato pela resposta. Deu certo
    – Eduardo
    3/08/2017 às 22:19

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .